﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace DynamicMVVM.SL
{
    public abstract class DynamicModelBase : INotifyPropertyChanged
    {
        private bool _isLoading;

        public Object Model { get; private set; }

        public void SetPropertyValue(string propertyName, object obj)
        {
            if(_isLoading)
                return;

            var propertyInfo = TypeProperties.FirstOrDefault(x => x.Name == propertyName);

            if (propertyInfo != null)
            {
                propertyInfo.SetValue(Model, obj, null);
            }
        }

        public void SetModel(object model)
        {
            if(model == null)
                return;

            _isLoading = true;
            
            Model = model;

            //foreach (var propertyInfo in TypeProperties)
            //{
            //    try
            //    {
            //        var currVal = propertyInfo.GetValue(model, null);
            //        propertyInfo.SetValue(this, currVal, null);
            //    }
            //    catch (Exception exception)
            //    {
            //        ;
            //    }
            //}

            _isLoading = false;
        }

        public List<PropertyInfo> TypeProperties { get; set; }

        #region Implementation of INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        protected void RaisePropertyChanged<T>(Expression<Func<T>> property)
        {
            if (PropertyChanged == null) return;

            var expression = property.Body as MemberExpression;
            if (expression == null) return;
            var member = expression.Member;
            PropertyChanged(this, new PropertyChangedEventArgs(member.Name));
        }

        #endregion
    }
}
